home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13088 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.iadfw.net!usenet
  2. From: jakramer@airmail.net (JA Kramer)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Need to get value from 2-D matrix
  5. Date: Thu, 04 Apr 1996 17:35:30 GMT
  6. Organization: customer of Internet America
  7. Message-ID: <4k0psu$lit@news-f.iadfw.net>
  8. References: <DotDpo.6o2@news.uwindsor.ca>
  9. NNTP-Posting-Host: dal17-20.ppp.iadfw.net
  10. X-Newsreader: Forte Free Agent v0.55
  11.  
  12. kima@uwindsor.ca (Sam Kim) wrote:
  13.  
  14.  
  15. >I'm writing a program that reads in a 2-D matrix from binary.  I am
  16. >useless with structures, so I'm trying to do this with arrays and
  17. >pointers.
  18.  
  19. >Question :  How do I read in the values?
  20.  
  21. >I have : 
  22.  
  23. >for (i=0; i<n; i++)
  24. >  for (j=0; j<n; j++)
  25. >    {
  26. >      fread(&ptr,1,1,fp)
  27. >      matrix[i][j] = ptr;
  28. >      ptr++;
  29. >    }
  30.  
  31. >Shouldn't this work?
  32.  
  33. Sam, you really haven't given enough information to fully evaluate
  34. your code segment. Here's a few questions/comments you may find
  35. helpful.
  36.  
  37. 1) What is the binary format? Were the original matrix values written
  38. as integers (long or short) or floats (single or double)? In order to
  39. read the data correctly you will need to use the same data type. (I'll
  40. assume that both the writing and reading CPUs are the same and you
  41. don't need to worry about Little/Big Endians!)
  42.  
  43. 2) Is the file itself formatted in any way? I.e. was the matrix
  44. written out by rows with each row delimited by CR/LF?
  45.  
  46. 3) Given your code segment, "ptr" only needs to be the size of one
  47. matrix element and not a buffer. If this was your intent then "ptr++"
  48. is walking over the rest of your program!
  49.  
  50. 4) Here's your most efficient implementation given that the person who
  51. wrote the matrix acted accordingly and that the underlying data value
  52. was an integer.
  53.  
  54. int matrix[N][M];
  55. .
  56. .
  57. .
  58. fread (matrix, sizeof( int),  N*M, fp);
  59. .
  60. .
  61. .
  62.  
  63. It doesn't get much simpler, or faster, than this. Don't forget to add
  64. error handling. Note also, that with DOS I believe that there's a
  65. limit of 64Kbytes that you can read at one time. Also, you'll need to
  66. open the file appropriately.
  67.  
  68.